//判断ele是否是parentEle的子元素或者直接就是parentEle
function parents(ele,parentEle){
	let parentNode = null
	if(ele){
		while(ele){
			if(ele ===  parentEle){
				parentNode = ele
				break;
			}
			ele = ele.parentNode
		}
	}
	return parentNode
}
export default class SmartScroll{
	constructor(container,scrollContainer) {
	  this.container = container
		if(this.container.dataset['bindscroll']){
			throw new Error('该元素已绑定请勿多次绑定!')
		}
		this.scrollContainer = scrollContainer
		if(this.selectorScrollable){
			throw new Error('滚动元素的容器必传!')
		}
		this.init()
	}
	init(){
		this.data = {posY: 0,maxscroll: 0}
		this.container.addEventListener('touchstart',(event)=>{
			let events = event.touches[0] || event
			if (!event.target) {
				return
			}
			let elScroll,elTarget = event.target
			// 获取标记的滚动元素，自身或子元素皆可
			if (elTarget === this.scrollContainer) {
				elScroll = this.scrollContainer
			} else if (parents(elTarget,this.scrollContainer)) {
				elScroll = this.scrollContainer
			}else{
				elScroll = null
			}
			if (!elScroll) {
				return false
			}
			// 当前滚动元素标记
			this.data.elScroll = elScroll
			// 垂直位置标记
			this.data.posY = events.pageY
			this.data.scrollY = elScroll.scrollTop
			// 是否可以滚动
			this.data.maxscroll = elScroll.scrollHeight - elScroll.clientHeight
		})
		this.container.addEventListener('touchmove',(event)=>{
			// 滚动元素
			let elScroll = this.data.elScroll
			if (this.data.maxscroll <= 0 || !elScroll) {
				// 禁止滚动
				event.preventDefault()
			}
			if(elScroll){
				// 当前的滚动高度
				let scrollTop = elScroll.scrollTop
				// 现在移动的垂直位置，用来判断是往上移动还是往下
				let events = event.touches[0] || event
				// 移动距离
				let distanceY = events.pageY - this.data.posY;
				// 上下边缘检测
				if (distanceY > 0 && scrollTop == 0) {
					// 往上滑，并且到头
					// 禁止滚动的默认行为
					event.preventDefault();
					return;
				}
				// 下边缘检测
				if (distanceY < 0 && (scrollTop + 1 >= this.data.maxscroll)) {
					// 往下滑，并且到头
					// 禁止滚动的默认行为
					event.preventDefault();
					return;
				}
			}
		})
		this.container.addEventListener('touchend',()=>{
			this.data.maxscroll = 0
		})
		this.container.setAttribute('data-bindscroll',true)
	}
} 